<template>
  <div class="login-page">
    <div class="login-container">
      <div class="login-header">
        <h1>校园二手书交易平台</h1>
        <div class="login-tabs">
          <button 
            class="tab-btn" 
            :class="{ active: activeTab === 'login' }" 
            @click="activeTab = 'login'"
          >
            登录
          </button>
          <button 
            class="tab-btn" 
            :class="{ active: activeTab === 'register' }" 
            @click="activeTab = 'register'"
          >
            注册
          </button>
        </div>
      </div>
      
      <div class="login-content">
        <!-- 登录表单 -->
        <form v-if="activeTab === 'login'" @submit.prevent="handleLogin" class="login-form">
          <div class="form-group">
            <label for="login-username">用户名</label>
            <input 
              type="text" 
              id="login-username" 
              v-model="loginForm.username" 
              @input="filterSpaces('login-username')"
              placeholder="请输入用户名"
              required
            >
          </div>
          
          <div class="form-group">
            <label for="login-password">密码</label>
            <div class="password-input">
              <input 
                :type="showPassword ? 'text' : 'password'" 
                id="login-password" 
                v-model="loginForm.password" 
                @input="filterSpaces('login-password')"
                placeholder="请输入密码"
                required
              >
              <button 
                type="button" 
                class="toggle-password" 
                @click="showPassword = !showPassword"
              >
                {{ showPassword ? '隐藏' : '显示' }}
              </button>
            </div>
          </div>
          
          <div class="form-actions">
            <div class="remember-forgot">
              <label class="remember-me">
                <input type="checkbox" v-model="loginForm.remember">
                <span>记住我</span>
              </label>
              <a href="#" class="forgot-password" @click.prevent="forgotPassword">忘记密码？</a>
            </div>
            
            <button 
              type="submit" 
              class="btn-submit" 
              :disabled="isSubmitting"
            >
              {{ isSubmitting ? '登录中...' : '登录' }}
            </button>
          </div>
        </form>
        
        <!-- 注册表单 -->
        <form v-if="activeTab === 'register'" @submit.prevent="handleRegister" class="register-form">
          <div class="form-group">
            <label for="register-username">用户名</label>
            <input 
              type="text" 
              id="register-username" 
              v-model="registerForm.username" 
              @blur="validateUsername"
              @input="filterSpaces('username')"
              placeholder="请输入用户名"
              required
            >
            <span class="error-message" v-if="errors.username">{{ errors.username }}</span>
          </div>
          
          <div class="form-group">
            <label for="register-realname">真实姓名</label>
            <input 
              type="text" 
              id="register-realname" 
              v-model="registerForm.real_name" 
              @blur="validateRealName"
              @input="filterSpaces('real_name')"
              placeholder="请输入真实姓名"
              required
            >
            <span class="error-message" v-if="errors.real_name">{{ errors.real_name }}</span>
          </div>
          
          <div class="form-group">
            <label for="register-student-id">学号</label>
            <input 
              type="text" 
              id="register-student-id" 
              v-model="registerForm.student_id" 
              @blur="validateStudentId"
              @input="filterSpaces('student_id')"
              placeholder="请输入学号"
              required
            >
            <span class="error-message" v-if="errors.student_id">{{ errors.student_id }}</span>
          </div>
          
          <div class="form-group">
            <label for="register-department">所在学院</label>
            <input 
              type="text" 
              id="register-department" 
              v-model="registerForm.department" 
              @blur="validateDepartment"
              @input="filterSpaces('department')"
              placeholder="请输入所在学院或部门"
              required
            >
            <span class="error-message" v-if="errors.department">{{ errors.department }}</span>
          </div>
          
          <div class="form-group">
            <label for="register-email">邮箱</label>
            <input 
              type="email" 
              id="register-email" 
              v-model="registerForm.email" 
              @blur="validateEmail"
              @input="filterSpaces('email')"
              placeholder="请输入邮箱"
              required
            >
            <span class="error-message" v-if="errors.email">{{ errors.email }}</span>
          </div>
          
          <div class="form-group">
            <label for="register-phone">手机号</label>
            <input 
              type="tel" 
              id="register-phone" 
              v-model="registerForm.phone" 
              @blur="validatePhone"
              @input="filterSpaces('phone')"
              placeholder="请输入手机号"
              pattern="[0-9]{11}"
            >
            <span class="error-message" v-if="errors.phone">{{ errors.phone }}</span>
          </div>
          
          <div class="form-group">
            <label for="register-wechat">微信号</label>
            <input 
              type="text" 
              id="register-wechat" 
              v-model="registerForm.wechat" 
              @input="filterSpaces('wechat')"
              placeholder="请输入微信号"
            >
          </div>
          
          <div class="form-group">
            <label for="register-password">密码</label>
            <div class="password-input">
              <input 
                :type="showRegPassword ? 'text' : 'password'" 
                id="register-password" 
                v-model="registerForm.password" 
                @blur="validatePassword"
                @input="filterSpaces('password')"
                placeholder="请设置密码"
                required
              >
              <button 
                type="button" 
                class="toggle-password" 
                @click="showRegPassword = !showRegPassword"
              >
                {{ showRegPassword ? '隐藏' : '显示' }}
              </button>
            </div>
            <span class="error-message" v-if="errors.password">{{ errors.password }}</span>
            <small class="password-hint">密码必须至少8位，且包含字母和数字</small>
          </div>
          
          <div class="form-group">
            <label for="register-confirm-password">确认密码</label>
            <div class="password-input">
              <input 
                :type="showRegPassword ? 'text' : 'password'" 
                id="register-confirm-password" 
                v-model="registerForm.confirmPassword" 
                @blur="validateConfirmPassword"
                @input="filterSpaces('confirmPassword')"
                placeholder="请再次输入密码"
                required
              >
            </div>
            <span class="error-message" v-if="errors.confirmPassword">{{ errors.confirmPassword }}</span>
          </div>
          
          <div class="form-group terms">
            <label class="checkbox-label">
              <input 
                type="checkbox" 
                v-model="registerForm.agreeTerms"
                required
              >
              <span>我已阅读并同意<a href="#" @click.prevent="showTerms">用户协议</a>和<a href="#" @click.prevent="showPrivacy">隐私政策</a></span>
            </label>
          </div>
          
          <button 
            type="submit" 
            class="btn-submit" 
            :disabled="isSubmitting"
          >
            {{ isSubmitting ? '注册中...' : '注册' }}
          </button>
        </form>
      </div>
    </div>
    <Toast 
      :message="toastMessage" 
      :type="toastType" 
      :visible="toastVisible" 
      @close="toastVisible = false" 
    />
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { useRouter } from 'vue-router'
import Toast from '@/components/Toast.vue'
import api from '@/api/apiClient'
import websocketService from '@/services/websocketService'

const router = useRouter()
const activeTab = ref('login')
const isSubmitting = ref(false)
const showPassword = ref(false)
const showRegPassword = ref(false)
const toastVisible = ref(false)
const toastMessage = ref('')
const toastType = ref('info')

// 显示提示消息
const showToast = (message, type = 'info') => {
  toastMessage.value = message
  toastType.value = type
  toastVisible.value = true
  
  // 3秒后自动关闭
  setTimeout(() => {
    toastVisible.value = false
  }, 3000)
}

// 登录表单
const loginForm = reactive({
  username: '',
  password: '',
  remember: false
})

// 注册表单
const registerForm = reactive({
  username: '',
  real_name: '',
  student_id: '',
  department: '',
  email: '',
  phone: '',
  wechat: '',
  password: '',
  confirmPassword: '',
  agreeTerms: false
})

// 表单验证错误信息
const errors = reactive({
  username: '',
  real_name: '',
  student_id: '',
  department: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: ''
})

// 验证用户名
const validateUsername = () => {
  if (!registerForm.username) {
    errors.username = '请输入用户名'
    return false
  }
  
  if (registerForm.username.length < 3) {
    errors.username = '用户名长度不能少于3位'
    return false
  }
  
  if (/\s/.test(registerForm.username)) {
    errors.username = '用户名不能包含空格'
    return false
  }
  
  errors.username = ''
  return true
}

// 验证姓名（不为空且长度合适）
const validateRealName = () => {
  if (!registerForm.real_name) {
    errors.real_name = '请输入姓名'
    return false
  }
  
  errors.real_name = ''
  return true
}

// 验证学号
const validateStudentId = () => {
  if (!registerForm.student_id) {
    errors.student_id = '请输入学号'
    return false
  }
  
  errors.student_id = ''
  return true
}

// 验证学院
const validateDepartment = () => {
  if (!registerForm.department) {
    errors.department = '请输入所在学院/部门'
    return false
  }
  
  errors.department = ''
  return true
}

// 验证邮箱
const validateEmail = () => {
  if (!registerForm.email) {
    errors.email = '请输入邮箱'
    return false
  }
  
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(registerForm.email)) {
    errors.email = '请输入有效的邮箱地址'
    return false
  }
  
  errors.email = ''
  return true
}

// 验证手机号
const validatePhone = () => {
  if (!registerForm.phone) {
    // 手机号可选，不验证
    return true
  }
  
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(registerForm.phone)) {
    errors.phone = '请输入有效的手机号'
    return false
  }
  
  errors.phone = ''
  return true
}

// 验证密码
const validatePassword = () => {
  if (!registerForm.password) {
    errors.password = '请输入密码'
    return false
  }
  
  if (registerForm.password.length < 8) {
    errors.password = '密码长度至少为8位'
    return false
  }
  
  if (/\s/.test(registerForm.password)) {
    errors.password = '密码不能包含空格'
    return false
  }
  
  const hasLetter = /[a-zA-Z]/.test(registerForm.password)
  const hasNumber = /[0-9]/.test(registerForm.password)
  
  if (!hasLetter || !hasNumber) {
    errors.password = '密码必须包含字母和数字'
    return false
  }
  
  errors.password = ''
  return true
}

// 验证确认密码
const validateConfirmPassword = () => {
  if (!registerForm.confirmPassword) {
    errors.confirmPassword = '请确认密码'
    return false
  }
  
  if (registerForm.confirmPassword !== registerForm.password) {
    errors.confirmPassword = '两次输入的密码不一致'
    return false
  }
  
  errors.confirmPassword = ''
  return true
}

// 表单整体验证
const validateForm = () => {
  const usernameValid = validateUsername()
  const realNameValid = validateRealName()
  const studentIdValid = validateStudentId()
  const departmentValid = validateDepartment()
  const emailValid = validateEmail()
  const phoneValid = validatePhone()
  const passwordValid = validatePassword()
  const confirmPasswordValid = validateConfirmPassword()
  
  return usernameValid && realNameValid && studentIdValid && departmentValid && emailValid && 
         phoneValid && passwordValid && confirmPasswordValid
}

// 确认密码是否匹配
const passwordsMatch = computed(() => {
  return !registerForm.confirmPassword || registerForm.password === registerForm.confirmPassword
})

// 登录表单验证
const validateLoginForm = () => {
  if (!loginForm.username) {
    showToast('请输入用户名', 'error')
    return false
  }
  
  if (!loginForm.password) {
    showToast('请输入密码', 'error')
    return false
  }
  
  return true
}

// 登录处理
const handleLogin = async () => {
  try {
    if (!validateLoginForm()) {
      return;
    }
    
    isSubmitting.value = true;
    
    const response = await api.user.login({
      username: loginForm.username,
      password: loginForm.password
    });
    
    console.log('登录响应:', response);
    
    // 登录成功后会自动保存token和用户角色（在apiClient.js中处理）
    showToast('登录成功', 'success');
    
    // 简单检查是否有用户ID存储在localStorage中
    setTimeout(() => {
      try {
        const userId = JSON.parse(localStorage.getItem('user') || '{}').id || localStorage.getItem('userId');
        console.log('登录后获取到的用户ID:', userId);
        
        // 尝试连接WebSocket
        if (userId) {
          console.log('连接WebSocket, 用户ID:', userId);
          websocketService.disconnect(); // 先断开旧连接
          websocketService.connect(userId);
        }
      } catch (e) {
        console.error('检查localStorage失败:', e);
      }
    }, 500);
    
    // 获取用户角色并跳转
    const userRole = response.role;
    
    if (userRole === 'ADMIN') {
      console.log('跳转到管理后台');
      router.push('/admin/dashboard');
    } else {
      console.log('跳转到首页');
      router.push('/');
    }
  } catch (error) {
    console.error('登录错误:', error);
    showToast(error.message || '登录失败', 'error');
  } finally {
    isSubmitting.value = false;
  }
};

// 注册处理
const handleRegister = async () => {
  if (!validateForm()) {
    showToast('请检查表单信息', 'error')
    return
  }
  
  if (!registerForm.agreeTerms) {
    showToast('请阅读并同意用户协议和隐私政策', 'warning')
    return
  }
  
  isSubmitting.value = true
  
  try {
    // 调用注册API
    const response = await api.user.register({
      username: registerForm.username,
      real_name: registerForm.real_name,
      student_id: registerForm.student_id,
      department: registerForm.department,
      email: registerForm.email,
      phone: registerForm.phone,
      wechat: registerForm.wechat,
      password: registerForm.password
    })
    
    console.log('注册API响应:', response)
    
    showToast('注册成功！', 'success')
    // 切换到登录选项卡
    activeTab.value = 'login'
    // 预填充用户名以方便登录
    loginForm.username = registerForm.username
  } catch (error) {
    console.error('注册失败:', error)
    
    // 直接使用后端返回的错误消息
    if (error.message) {
      showToast(error.message, 'error')
    } else {
      showToast('注册失败，请稍后再试', 'error')
    }
  } finally {
    isSubmitting.value = false
  }
}

// 忘记密码
const forgotPassword = () => {
  showToast('重置密码功能暂未开放，请联系管理员', 'info')
}

// 显示服务条款
const showTerms = () => {
  showToast('用户协议页面将在新窗口打开', 'info')
  // window.open('/terms', '_blank')
}

// 显示隐私政策
const showPrivacy = () => {
  showToast('隐私政策页面将在新窗口打开', 'info')
  // window.open('/privacy', '_blank')
}

// 过滤输入的空格
const filterSpaces = (field) => {
  if (field === 'login-username') {
    loginForm.username = loginForm.username.replace(/\s/g, '')
  } else if (field === 'login-password') {
    loginForm.password = loginForm.password.replace(/\s/g, '')
  } else if (field === 'username') {
    registerForm.username = registerForm.username.replace(/\s/g, '')
  } else if (field === 'password') {
    registerForm.password = registerForm.password.replace(/\s/g, '')
  } else if (field === 'confirmPassword') {
    registerForm.confirmPassword = registerForm.confirmPassword.replace(/\s/g, '')
  } else if (field === 'real_name') {
    registerForm.real_name = registerForm.real_name.replace(/\s/g, '')
  } else if (field === 'student_id') {
    registerForm.student_id = registerForm.student_id.replace(/\s/g, '')
  } else if (field === 'department') {
    registerForm.department = registerForm.department.replace(/\s/g, '')
  } else if (field === 'email') {
    registerForm.email = registerForm.email.replace(/\s/g, '')
  } else if (field === 'phone') {
    registerForm.phone = registerForm.phone.replace(/\s/g, '')
  } else if (field === 'wechat') {
    registerForm.wechat = registerForm.wechat.replace(/\s/g, '')
  }
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f3f4f6;
  padding: 2rem;
}

.login-container {
  width: 100%;
  max-width: 500px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.login-header {
  text-align: center;
  padding: 2rem 1rem;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e5e7eb;
}

.login-header h1 {
  margin: 0 0 1.5rem;
  color: #3b82f6;
  font-size: 1.8rem;
}

.login-tabs {
  display: flex;
  justify-content: center;
  gap: 1rem;
}

.tab-btn {
  padding: 0.5rem 2rem;
  border: none;
  background: none;
  color: #6b7280;
  font-weight: 500;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.2s;
}

.tab-btn:hover {
  color: #3b82f6;
}

.tab-btn.active {
  color: #3b82f6;
  border-bottom-color: #3b82f6;
}

.login-content {
  padding: 2rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #374151;
}

input[type="text"],
input[type="password"],
input[type="email"],
input[type="tel"] {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 1rem;
}

input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.password-input {
  position: relative;
  display: flex;
}

.password-input input {
  flex: 1;
  padding-right: 4rem;
}

.toggle-password {
  position: absolute;
  right: 0.5rem;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #6b7280;
  cursor: pointer;
  padding: 0.25rem 0.5rem;
}

.toggle-password:hover {
  color: #3b82f6;
}

.form-actions {
  margin-top: 2rem;
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.remember-me {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.remember-me input {
  margin-right: 0.5rem;
}

.forgot-password {
  color: #3b82f6;
  text-decoration: none;
}

.forgot-password:hover {
  text-decoration: underline;
}

.btn-submit {
  width: 100%;
  padding: 0.75rem;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-submit:hover:not(:disabled) {
  background-color: #2563eb;
}

.btn-submit:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.terms-agreement {
  margin-bottom: 1.5rem;
}

.terms-agreement a {
  color: #3b82f6;
  text-decoration: none;
}

.terms-agreement a:hover {
  text-decoration: underline;
}

.error-message {
  color: #ff4d4f;
  font-size: 0.8rem;
  margin-top: 0.25rem;
  display: block;
}

.password-hint {
  color: #666;
  font-size: 0.75rem;
  margin-top: 0.25rem;
  display: block;
}

.form-group.terms {
  margin-top: 1rem;
}

.checkbox-label {
  cursor: pointer;
  display: flex;
  align-items: flex-start;
}

.checkbox-label input[type="checkbox"] {
  margin-top: 0.25rem;
  margin-right: 0.5rem;
}

.checkbox-label a {
  color: #1890ff;
  text-decoration: none;
}

.checkbox-label a:hover {
  text-decoration: underline;
}

@media (max-width: 768px) {
  .login-container {
    max-width: 100%;
  }
  
  .login-page {
    padding: 1rem;
  }
}
</style>